# -*- coding: utf-8 -*-
import hashlib
import json
import random
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

# 新稻米
APP_CONF = {
    '1810080525': {  # dwc 支付宝 10-5000
        'API_KEY': '7d7b9b2e2bdb3fe4678b11841437fabc',
        'gateway': 'http://47.107.62.215:88/pay/gateway',
    },
    '1811140534': {  # zs 支付宝 10-5000
        'API_KEY': 'af1da70a150ec036c2203944f7e428dd',
        'gateway': 'http://47.107.62.215:88/pay/gateway',
    },
    '1811140535': {  # witch 支付宝 10-5000
        'API_KEY': '33a2f698528453c78ae1524a39c4fd61',
        'gateway': 'http://47.107.62.215:88/pay/gateway',
    },
    '1811260541': {  # dwc 支付宝 10-5000
        'API_KEY': 'beb6ee2631c1b314c31d0fdc59dacdc6',
        'gateway': 'http://47.107.62.215:88/pay/gateway',
    },
    '1811260539': {  # zs 支付宝 10-5000
        'API_KEY': '78cc8f0fd3fff4ac500290c3b86e107d',
        'gateway': 'http://47.107.62.215:88/pay/gateway',
    },
    '1811260540': {  # witch 支付宝 10-5000
        'API_KEY': '4fda492566c21c2cfc0e4dfcab458774',
        'gateway': 'http://47.107.62.215:88/pay/gateway',
    },
    '1903220895': {  # dwc 支付宝 10-5000
        'API_KEY': '5a061790ef5446edccd6c65361b3dff5',
        'gateway': 'http://pay.xiaoguipay.com:88/pay/gateway',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(params, key):
    s = 'app_id={}&notify_url={}&out_trade_no={}&total_amount={}&trade_type={}{}'.format(
        params['app_id'], params['notify_url'], params['out_trade_no'],
        params['total_amount'], params['trade_type'], key
    )
    _LOGGER.info('xindaomipay sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest().lower()
    return sign


def generate_notify_sign(params, key):
    s = 'out_trade_no={}&total_amount={}&trade_status={}{}'.format(
        params['out_trade_no'], params['total_amount'],
        params['trade_status'], key
    )
    _LOGGER.info('xindaomipay notify sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("xindaomipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        payType = 'ALIPAY_H5'
    return payType


def _build_query_string(params):
    s = 'app_id={}&trade_type={}&total_amount={}&out_trade_no={}&notify_url={}&interface_version={}&sign={}'.format(
        params['app_id'], params['trade_type'],
        params['total_amount'], params['out_trade_no'],
        params['notify_url'], params['interface_version'],
        params['sign']
    )
    return s


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if 10 <= pay_amount == int(pay_amount):
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount) / 100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(app_id)
    # pay_amount = _fix_pay_amount(pay, pay_amount)
    parameter_dict = OrderedDict((
        ('app_id', app_id),
        ('trade_type', _get_pay_type(service)),
        ('total_amount', str(int(pay_amount * 100))),  # 单位：分
        ('out_trade_no', str(pay.id)),
        ('notify_url', '{}/pay/api/{}/xindaomipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('interface_version', 'V2.0'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, key)
    data = json.dumps(parameter_dict)
    url = _get_gateway(app_id) + '?' + _build_query_string(parameter_dict)
    _LOGGER.info("xindaomipay create: url: %s, %s", url, data)
    return {'charge_info': url}


# success
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("xindaomipay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('xindaomipay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['trade_status']
    trade_no = data['trade_no']
    total_fee = float(data['total_amount']) / 100.0  # 对方回传单位：分

    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 1:为成功，其他值为失败
    if trade_status == 'SUCCESS':
        _LOGGER.info('xindaomipay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pass
